package org.martyn.danbooru.parsers.xml;

import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;

import org.martyn.danbooru.types.Post;
import org.martyn.danbooru.types.groups.PostGroup;
import org.martyn.danbooru.utils.DateUtils;
import org.martyn.danbooru.utils.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PostParser {

	public PostGroup Parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException{
		
		PostGroup postGroup = new PostGroup();
		
		Document document = XmlUtils.XmlDocumentParser(inputStream);

		inputStream.close();
		
		NodeList postsNodes = document.getElementsByTagName("posts");
		
		for(int i = 0; i < postsNodes.getLength(); i++)
		{
			Element element = (Element) postsNodes.item(0);
			
			postGroup.setPostCount(Long.parseLong(element.getAttribute("count")));
		}
		
		NodeList postNodes = document.getElementsByTagName("post");

		for (int i = 0; i < postNodes.getLength(); i++) {
			Element element = (Element) postNodes.item(i);
			Post postObj = new Post();
			
			postObj.setId(Long.parseLong(element.getAttribute("id")));
			postObj.setCreatedAt(DateUtils.ParseDate(element.getAttribute("created_at")));
			postObj.setScore(Integer.parseInt(element.getAttribute("score")));
			postObj.setAuthor(element.getAttribute("author"));
			postObj.setStatus(element.getAttribute("status"));
			postObj.setRating(element.getAttribute("rating"));
			postObj.setFileUrl(element.getAttribute("file_url"));
			postObj.setFileWidth(Integer.parseInt(element.getAttribute("width")));
			postObj.setFileHeight(Integer.parseInt(element.getAttribute("height")));
			postObj.setFileSize(Long.parseLong(element.getAttribute("file_size")));
			postObj.setFileMd5(element.getAttribute("md5"));
			postObj.setPreviewUrl(element.getAttribute("preview_url"));
			postObj.setPreviewWidth(Integer.parseInt(element.getAttribute("preview_width")));
			postObj.setPreviewHeight(Integer.parseInt(element.getAttribute("preview_height")));
			
			postGroup.add(postObj);	
		}
	
		return postGroup;
	}
}
